package ucm.module;
import air_cp5620.dao.DAO;
import javax.swing.JOptionPane;
import java.sql.*;
import ucm.controller.UC_SelInfoC;

public class UC_BuyM {
    private DAO dbCon = null;

    public UC_BuyM() {
        dbCon = new DAO();
    }


    public boolean buy(String id,String count,String userid)
    {
        String sql = null;
        Connection con = dbCon.getConnection();
        if (con == null) {
            return false;
        }
        try {
            Statement stmt = con.createStatement(ResultSet.CONCUR_UPDATABLE, ResultSet.CONCUR_UPDATABLE);
            sql = "select * from tbl_air_info where id ='" + id + "'";
            ResultSet res = stmt.executeQuery(sql);
            
            res.first();
            if (res.getString("id").equals("")) {
                 JOptionPane.showMessageDialog(null, "Id is not in database,please check!");
                 return false;
            }

            int buyCount = Integer.parseInt(count);
            int ticketcount = res.getInt("ticketcount");
            double price = res.getInt("price");

            if (ticketcount < buyCount) {
                 JOptionPane.showMessageDialog(null, "About the number of tickets purchased is the total number of votes,please check!");
                 return false;
            }
            else {
                stmt.executeUpdate("update tbl_air_info set ticketcount='" + (ticketcount - buyCount) + "' WHERE id = '" + id + "'");
                stmt.executeUpdate("insert into tbl_buy_info(Id,userid,count) values(" + id + ",'" + userid + "'," + buyCount + ")");

                if (buyCount >= 5) {
                    price = (price)*(buyCount)*(0.8);
                    JOptionPane.showMessageDialog(null, "Ticket purchase successful,Please pay:" + price + "yuan");
                }
                else {
                    price = (price)*(buyCount);
                    JOptionPane.showMessageDialog(null, "Ticket purchase successful,Please pay:" + price + "yuan");
                }

                
                UC_SelInfoC uc_sic = new UC_SelInfoC(userid,true);
                uc_sic.selectAll();
                return true;
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Buy ticket error");
            e.printStackTrace();
            return false;
        }
    }
}
